package cn.edu.xhu.library_management.common.handler;

import cn.edu.xhu.library_management.common.entity.R;
import cn.edu.xhu.library_management.common.exception.LibraryManagementException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: MMJ
 * @Date: 2022-01-14
 * @Description: 全局异常处理类
 * 注：一定要扫描这个类😊😊
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 指定出现什么异常，执行这个方法
    /*@ExceptionHandler(Exception.class)
    @ResponseBody   // 用于返回数据
    public R error(Exception e) {
        e.printStackTrace();
        return R.error().message("服务端报错");
    }*/
    // 自己定义的异常处理
    @ExceptionHandler(LibraryManagementException.class)
    public R error(LibraryManagementException e) {
        e.printStackTrace();
        return R.error().code(e.getCode().getCode()).message(e.getMsg());
    }

    // validated 校验异常处理类
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException m){
        BindingResult bindingResult = m.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        String errorMsg = fieldErrors.stream()
                .map(fieldError -> fieldError.getField() + ":" + fieldError.getDefaultMessage())
                .collect(Collectors.joining(","));
        return R.error(errorMsg);
    }
}
